package mh.log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A stream that redirect the flow to a specified logger.
 * 
 * @author Gianmarco Laggia
 * 
 */
public class LogOutputStream extends ByteArrayOutputStream {//java.io.OutputStream {

	//    static Logger logger = Logger.getLogger("");//LogOutputStream.class.getName());
	//    private char lineSeparatorEnd = 'n';
	private String	lineSeparator;
	private Logger	logger;
	private Level	level;

	//    private StringBuffer buffer = new StringBuffer();

	//    public void write(int b) throws IOException {
	//        char ch = (char) b;
	//        this.buffer.append(ch);
	//        if (ch == this.lineSeparatorEnd) {
	//            // Check on a char by char basis for speed
	//            String s = buffer.toString();
	//            if (s.indexOf(lineSeparator) != -1) {
	//                // The whole separator string is written
	//                logger.info(s.substring(0, s.length() - lineSeparator.length()));
	//                buffer.setLength(0);
	//            }
	//        }
	//    }
	/**
	 * Constructor
	 * 
	 * @param logger
	 *            the logger to send the stream
	 * @param level
	 *            what level will be sent
	 */
	public LogOutputStream(Logger logger, Level level) {
		super();
		this.logger = logger;
		this.level = level;
		this.lineSeparator = System.getProperty("line.separator");
	}

	@Override
	public void flush() throws IOException {

		String record;
		synchronized (this) {
			super.flush();
			record = this.toString();
			super.reset();

			if ((record.length() == 0) || record.equals(this.lineSeparator)) {
				// avoid empty records 
				return;
			}

			this.logger.logp(this.level, "", "", record);
		}
	}
}
